package com.homework.ch02;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/11/6
 * @Description:
 */
class JdbcUtils {
    //  Druid连接池（全局单例）
    private static DataSource dataSource;

    // 静态代码块：初始化连接池（仅加载一次）
    static {
        try {
            // 加载druid.properties配置文件
            Properties pro = new Properties();
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            // 创建Druid连接池
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            throw new RuntimeException("Druid连接池初始化失败", e);
        }
    }

    //提供私有无参构造器
    private JdbcUtils() {}
    //从数据库连接池中获取连接对象

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //关闭资源
    public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //关闭资源方法重载
    public static void close(PreparedStatement stmt, Connection conn) {
        close(null, stmt, conn);
    }
}
